package com.botann.projects.utils;


import org.apache.log4j.Logger;
import org.hibernate.query.Query;


/**
 * Not Use
 * Created by liushanguo on 2017/5/16.
 */
public final class HibernateUtils {
    private static Logger logger = Logger.getLogger(HibernateUtils.class);

    /**
     * 私有方法,设置查询参数
     * @param query Query
     * @param parameters List<Object> or String[] or common String or Object
     */
    public static void settingParameters(Query query, Object... parameters){
        if (parameters != null && parameters.length>0){
            for (int i = 0; i < parameters.length; i++){
                Object obj = parameters[i];
                query.setParameter(i,obj);
            }
        }
    }
//    public static String conditionsToHQL(Class clazz,Object conditions){
//        return conditionsToHQL(clazz,conditions,null);
//    }

    /**
     * 对象查询根据conditions orderBys生成 HQL
     * @param clazz         对象Class           not null
     * @param conditions    String[] or String null able
     * @param orderBys      String[] or String null able
     * @return HQL
     */
    public static String conditionsToHQL(Class clazz, Object conditions, Object orderBys){
        StringBuilder hqlBuilder = new StringBuilder("from ");
        hqlBuilder.append(clazz.getSimpleName());
        if (conditions != null) {
            if (conditions instanceof String) conditions = new String[]{(String) conditions};
            hqlBuilder.append(" where 1=1 ");
            int k = 0;
            for (int i =0;i<((String[])conditions).length;i++){
                String condition = ((String[])conditions)[i];
                if (condition.startsWith("||")) {
                    condition = condition.substring(2,condition.length());
                    hqlBuilder.append("or ");
                } else {
                    hqlBuilder.append("and ");
                }
                hqlBuilder.append(condition);
                if (condition.contains("between")) { // 末日期
                    hqlBuilder.append(" ?");
                    hqlBuilder.append(k);
                    hqlBuilder.append(" and ");
                    k++;
                    hqlBuilder.append("?");
                    hqlBuilder.append(k);
                } else {
                    hqlBuilder.append(" ?");
                    hqlBuilder.append(k);
                }
                hqlBuilder.append(" ");
                k++;
            }
//            for (int i =0;i<((String[])conditions).length;i++){
//                String condition = ((String[])conditions)[i];
//                if (condition.startsWith("||")) {
//                    condition = condition.substring(2,condition.length());
//                    hqlBuilder.append("or ");
//                } else {
//                    hqlBuilder.append("and ");
//                }
//                hqlBuilder.append(condition);
//                if (condition.contains("between")) { // 末日期
//                    hqlBuilder.append(" ?");
//                    hqlBuilder.append(i);
//                    hqlBuilder.append(" and ");
//                    i++;
//                    hqlBuilder.append("?");
//                    hqlBuilder.append(i);
//                } else {
//                    hqlBuilder.append(" ?");
//                    hqlBuilder.append(i);
//                }
//                hqlBuilder.append(" ");
//            }
        }
        if (orderBys != null) {
            hqlBuilder.append(" order by ");
            if (orderBys instanceof String[] ){
                int count = ((String[])orderBys).length;
                boolean moreOne = count>0;
                for (int i=0;i<count;i++){
                    hqlBuilder.append(((String[])orderBys)[i]);
                    hqlBuilder.append(", ");
                }
                if (moreOne) hqlBuilder.delete(hqlBuilder.length()-2,hqlBuilder.length());
            } else {
                hqlBuilder.append(orderBys);
            }
        }

        return hqlBuilder.toString();
    }


    /**
     * 打印 HQL 和 参数
     * @param hql           String
     * @param parameters    Object...
     */
    public static void logHqlAndParameters(String hql,Object... parameters){
        String paramStr;
        if (parameters == null) {
            paramStr = "{}";
        } else{
            StringBuilder stringBuilder = new StringBuilder();
            for (int i = 0; i< parameters.length;i++){
                Object obj = parameters[i];
                String objStr = null;
                if (obj != null) objStr = obj.toString();
                stringBuilder.append(objStr);
                stringBuilder.append("  ");
            }
            paramStr = stringBuilder.toString();
        }

        if (hql.contains("from")) {
            if (hql.startsWith("from")) {
                logger.info("\n----HQL查询: \n "+hql+"\n params: "+paramStr);
            } else {
                int fromIndex = hql.indexOf("from");
                int whereIndex = hql.indexOf("where");
                if (whereIndex > 0) {
                    logger.info("\n----HQL查询: \n"+
                            hql.substring(0,fromIndex)+"\n"+
                            hql.substring(fromIndex,whereIndex)+"\n"+
                            hql.substring(whereIndex)+
                            "\nparams: "+paramStr);
                } else {
                    logger.info("\n----HQL查询: \n"+
                            hql.substring(0,fromIndex)+"\n"+
                            hql.substring(fromIndex));
                }

            }

        } else {
            logger.info("\n----HQL查询: \n "+hql+"\n params: "+paramStr);
        }
    }

//    public interface CallToDo {
//        void transactionDo(void);
//    }
//    public static void TransactionBlock(SessionFactory factory, CallToDo toDo) {
//
//        Transaction tx = null;
//        try
//        {
//            tx = factory.getCurrentSession().beginTransaction();
//            toDo.transactionDo();
//            tx.commit();
//        }
//        catch (Exception e)
//        {
//            e.printStackTrace();
//            if (tx != null)
//            {
//                tx.rollback();
//            }
//            throw new RuntimeException(e.getMessage());
//        }
//    }

}
